using zhwy.saas.api.Entity.Sys;
using zhwy.saas.api.Extensions.Enum;
using zhwy.saas.api.Extensions.Log;
using zhwy.saas.api.Repository;
using zhwy.saas.api.Services.Sinterface.Sys;

namespace zhwy.saas.api.Services.Sys
{
    /// <summary>
    /// 系统角色服务实现
    /// </summary>
    public class SysRoleService : BaseService<RolesEntity>, ISysRoleService
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository">角色仓储接口</param>
        /// <param name="logger">日志服务</param>
        public SysRoleService(IBaseRepository<RolesEntity> repository, ILogExt logger)
            : base(repository, logger)
        {
        }

        /// <summary>
        /// 更新角色状态
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <param name="status">新状态</param>
        /// <returns>是否更新成功</returns>
        public async Task<bool> UpdateStatusAsync(long roleId, int status)
        {
            var role = await _repository.GetByIdAsync(roleId);
            if (role == null)
                return false;

            role.Status = status;
            return await _repository.UpdateAsync(role);
        }

        /// <summary>
        /// 获取指定用户的所有角色
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>角色列表</returns>
        public async Task<List<RolesEntity>> GetRolesByUserIdAsync(long userId)
        {
            // TODO: 实现根据用户ID查询角色列表，可能需要关联查询
            return await _repository.GetListAsync(r => r.Status == 1);
        }

        /// <summary>
        /// 批量分配角色权限
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <param name="permissionIds">权限ID列表</param>
        /// <returns>是否分配成功</returns>
        public async Task<bool> AssignPermissionsAsync(long roleId, List<long> permissionIds)
        {
            // TODO: 实现角色权限分配
            var role = await _repository.GetByIdAsync(roleId);
            if (role == null)
                return false;

            // 这里需要实现角色权限关联表的操作
            return true;
        }

        /// <summary>
        /// 获取租户默认角色
        /// </summary>
        /// <returns></returns>
        public async Task<RolesEntity> GetTenantDefaultInfo()
        {
            return await _repository.DbContext.Queryable<RolesEntity>()
                .Where(i => i.Code == EnumHelper.RoleCode.tenantadmin.ToString())
                .Where(i => i.Status == (int)EnumHelper.UsersStatus.use)
                .FirstAsync();
        }
    }
}